// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const db = cloud.database()
  const orders = db.collection('orders')
  const openid = wxContext.OPENID

  try {
    const { orderId } = event
    
    if (!orderId) {
      return {
        success: false,
        message: '订单ID不能为空'
      }
    }

    // 查询订单信息
    const orderRes = await orders.doc(orderId).get()
    
    if (!orderRes.data) {
      return {
        success: false,
        message: '订单不存在'
      }
    }

    // 检查订单是否属于当前用户
    if (orderRes.data._openid !== openid) {
      return {
        success: false,
        message: '无权访问此订单'
      }
    }

    const order = orderRes.data

    // 如果订单状态为pending，尝试查询微信支付状态
    if (order.payment_status === 'pending' && order.order_no) {
      try {
        const paymentResult = await cloud.cloudPay.queryOrder({
          outTradeNo: order.order_no
        })

        if (paymentResult.returnCode === 'SUCCESS') {
          if (paymentResult.tradeState === 'SUCCESS') {
            // 支付成功，更新订单状态
            await orders.doc(orderId).update({
              data: {
                payment_status: 'paid',
                transaction_id: paymentResult.transactionId,
                paid_at: new Date(),
                updated_at: new Date()
              }
            })

            return {
              success: true,
              payment_status: 'paid',
              message: '支付成功'
            }
          } else if (paymentResult.tradeState === 'CLOSED') {
            // 订单已关闭
            await orders.doc(orderId).update({
              data: {
                payment_status: 'failed',
                updated_at: new Date()
              }
            })

            return {
              success: true,
              payment_status: 'failed',
              message: '订单已关闭'
            }
          } else {
            // 其他状态（如NOTPAY、USERPAYING等）
            return {
              success: true,
              payment_status: order.payment_status,
              message: '订单处理中'
            }
          }
        }
      } catch (error) {
        console.error('查询支付状态失败：', error)
      }
    }

    return {
      success: true,
      payment_status: order.payment_status,
      message: '查询成功'
    }
  } catch (error) {
    console.error('查询订单状态失败：', error)
    return {
      success: false,
      message: '查询失败'
    }
  }
} 